package com.mallbook.model.utils;

import com.mallbook.model.exception.ServiceException;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.ibatis.session.SqlSession;

import java.lang.reflect.Method;

/**
 * @Author 宋明松
 * @Version V1.0.0
 * @Date 2022-06-24
 * 动态代理
 */
public class ProxyFactory<T> {

    public static <T> T getProxy(Class<T> c) {
        Enhancer e = new Enhancer();
        e.setSuperclass(c);
        e.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object result = null;
                SqlSession session = MybatisUtils.getSession();
                try {
                    result = methodProxy.invokeSuper(o, objects);
                    session.commit();
                } catch (PersistenceException e) {
                    session.rollback();
                    e.printStackTrace();
                    throw new ServiceException("数据操作失败", e);
                } finally {
                    session.close();
                    
                }

                return result;
            }
        });
        return (T) e.create();
    }
}
